package com.jelly.config.shiro.filter;

import com.jelly.common.constant.ShiroConstant;
import com.jelly.config.redis.session.RedisSessionDAO;
import com.jelly.config.shiro.token.TokenUtil;
import com.jelly.web.modules.staff.user.domain.User;
import com.jelly.web.modules.staff.user.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;

/**
 * <h4>功能:【自定义用户过滤器】【创建人：QIAOLIANG】</h4>
 *
 * @时间:2018/7/5 0005 9:34
 * @备注:<h4></h4>
 */
public class UserFilter extends AccessControlFilter {

    @Autowired
    private IUserService userService;

    private Cache<String, Deque<String>> cache;

    //设置Cache的key的前缀
    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache(ShiroConstant.SHIROREDISCACHE);
    }

    /**
     * @author QL
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        Subject subject = getSubject(servletRequest, servletResponse);
        if(!subject.isAuthenticated() && !subject.isRemembered()) {
            //如果没有登录，直接进行之后的流程
            return true;
        }

        User user = (User) subject.getPrincipal();
        String username = "info"+user.getLoginAccount();
        //读取缓存   没有就跳过
        Deque<String> deque = cache.get(username);
        if(null != deque){
            if(deque.contains("update")){
                User users = userService.getLoginAccount(user.getLoginAccount());
                PrincipalCollection principalCollection = subject.getPrincipals();
                String realmName = principalCollection.getRealmNames().iterator().next();
                PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(users, realmName);
                subject.runAs(newPrincipalCollection);
                cache.remove(username);
            }else{
                TokenUtil.logout();
            }
        }

        return true;
    }

    /**
     * @author QL
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }

}